package com.adnaan.backend.service.impl;

import com.adnaan.backend.common.mail.service.EmailService;
import com.adnaan.backend.entity.AfterSales;
import com.adnaan.backend.entity.Order;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.entity.SystemMessage;
import com.adnaan.backend.mapper.SystemMessageMapper;
import com.adnaan.backend.service.AfterSalesService;
import com.adnaan.backend.service.OrderService;
import com.adnaan.backend.service.SysUserService;
import com.adnaan.backend.service.SystemMessageService;
import com.adnaan.backend.websocket.SystemMessageWebSocketHandler;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, SystemMessage> implements SystemMessageService {

    @Resource
    private SystemMessageWebSocketHandler systemMessageWebSocketHandler;

    @Resource
    private OrderService orderService;

    @Resource
    private AfterSalesService afterSalesService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private EmailService emailService;

    @Override
    public void sendMessageToUser(SystemMessage message) {
        message.setCreateTime(new Date());
        message.setIsRead(0);
        save(message);
        systemMessageWebSocketHandler.sendMessageToUser(message);
    }

    // 广播消息
    @Override
    public void broadcastMessage(SystemMessage message) {
        message.setCreateTime(new Date());
        message.setIsRead(0);
        save(message);
        systemMessageWebSocketHandler.broadcastMessage(message);
    }

    @Override
    public long getUnreadCount(Long userId) {
        return count(new LambdaQueryWrapper<SystemMessage>()
                .eq(SystemMessage::getReceiverId, userId)
                .eq(SystemMessage::getIsRead, 0));
    }

    @Override
    public Page<SystemMessage> getUserMessages(Long userId, Page<SystemMessage> page) {
        return page(page, new LambdaQueryWrapper<SystemMessage>()
                .eq(SystemMessage::getReceiverId, userId)
                .orderByDesc(SystemMessage::getCreateTime));
    }

    @Override
    public void markAsRead(Long messageId) {
        SystemMessage message = getById(messageId);
        if (message != null) {
            message.setIsRead(1);
            updateById(message);
        }
    }

    @Override
    public void markAllAsRead(Long userId) {
        lambdaUpdate()
                .eq(SystemMessage::getReceiverId, userId)
                .eq(SystemMessage::getIsRead, 0)
                .set(SystemMessage::getIsRead, 1)
                .update();
    }

    @Override
    public void createOrderMessage(Long orderId, Long userId) {
        Order order = orderService.getById(orderId);
        if (order != null) {
            SystemMessage message = SystemMessage.builder()
                    .type("order")
                    .title("新订单通知")
                    .content(String.format("您有一个新的订单（订单号：%s）需要处理", order.getOrderNo()))
                    .receiverId(userId)
                    .businessId(orderId)
                    .build();
            sendMessageToUser(message);
        }
    }

    @Override
    public void createAfterSalesMessage(Long afterSalesId, Long userId) {
        AfterSales afterSales = afterSalesService.getById(afterSalesId);
        if (afterSales != null) {
            Order order = orderService.getById(afterSales.getOrderId());
            SystemMessage message = SystemMessage.builder()
                    .type("after_sales")
                    .title("售后申请通知")
                    .content(String.format("订单（%s）有新的售后申请需要处理", order.getOrderNo()))
                    .receiverId(userId)
                    .businessId(afterSalesId)
                    .build();
            sendMessageToUser(message);
        }
    }

    @Override
    public void createOrderCancelMessage(Long orderId, Long userId) {
        Order order = orderService.getById(orderId);
        if (order != null) {
            SystemMessage message = SystemMessage.builder()
                    .type("order")
                    .title("订单已取消")
                    .content(String.format("您有订单（%s）因超过24小时未支付已自动取消", order.getOrderNo()))
                    .receiverId(userId)
                    .businessId(orderId)
                    .build();
            sendMessageToUser(message);
        }
    }

    @Override
    public void createOrderRemindMessage(Long orderId, Long userId) {
        Order order = orderService.getById(orderId);
        if (order != null) {
            SystemMessage message = SystemMessage.builder()
                    .type("order")
                    .title("订单提醒")
                    .content(String.format("用户订单（%s）提醒您及时发货，请及时处理", order.getOrderNo()))
                    .receiverId(userId)
                    .businessId(orderId)
                    .build();
            sendMessageToUser(message);
        }
    }

    @Override
    public List<SystemMessage> getLatestUnreadMessages(Long userId, Integer limit) {
        return baseMapper.selectList(new LambdaQueryWrapper<SystemMessage>()
                .eq(SystemMessage::getReceiverId, userId)
                .eq(SystemMessage::getIsRead, false)
                .orderByDesc(SystemMessage::getCreateTime)
                .last("LIMIT " + limit));
    }

    @Override
    public void applyPass(Long userId) {
        SysUser user = sysUserService.getById(userId);
        Map<String, Object> model = new HashMap<>();
        model.put("username", user.getUsername());
        model.put("email", user.getEmail());
        model.put("approvalTime", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        model.put("loginUrl", "https://admin.adnaan.cn");
        model.put("logo", "https://admin.adnaan.cn/favicon.ico");
        model.put("year", LocalDate.now().getYear());
        model.put("companyName", "中草药识别系统");
        emailService.sendTemplateMailAsync(user.getEmail(), "账号申请通过通知", "account-approved.html", model);
    }

    @Override
    public void applyRefuse(Long userId, String reason) {
        SysUser user = sysUserService.getById(userId);
        emailService.sendSimpleMail(user.getEmail(), "账号申请被拒绝通知", "您的账号申请被拒绝，原因：" + reason);
    }
} 